import axios from "axios";
import { message } from 'ant-design-vue';
import router from "../router";

const service = axios.create({
  baseURL: `${location.protocol}//${location.host}/web`,
  timeout: 30000,
  headers: { "X-Requested-With": "XMLHttpRequest" },
});

axios.defaults.withCredentials = true;
axios.defaults.headers.common["Content-Type"] = "application/json";
// axios.defaults.headers.common['token'] = sessionStorage.token

service.interceptors.request.use((config) => {
  config.headers.common["Authorization"] = sessionStorage.token;
  // config.headers.common['token'] = sessionStorage.token
  return config;
}),
  (error: Error) => {
    Promise.reject(error);
  };

service.interceptors.response.use(
  (res) => {
    if (res.status === 400) {
      sessionStorage.token = "";
      location.reload();
    }
    if (res.data.success) {
      return res.data;
    }
    if (res.data.msgCode == "401") {
      sessionStorage.token = "";
      location.reload();
    }
    message.error(res.data.message || res.data.msg);
    return Promise.reject(res.data);
  },
  (error) => {
    if (JSON.stringify(error).indexOf("code 400") > 0) {
      sessionStorage.removeItem("token");
      router.push("/login");
      message.error('账号验证过期, 请重新登录');
    }
    const errorMessage = error.response.status === 500 ? "网络异常" : error.response.data.message || error.response.data.msg; //这里报错信息

    if (error.response.status === 401) {
      message.error('用户未授权');
      sessionStorage.token = "";
      location.reload();
    }
    message.error(errorMessage);
    return Promise.reject(error);
  }
);

export default service;
